package com.chat.simplechat.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chat.simplechat.constant.WebSocketConstant;
import com.chat.simplechat.entity.LoginUser;
import com.chat.simplechat.response.Result;
import com.chat.simplechat.websocket.SpringWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户上线事件监听
 * @author wangyabin
 * @date 2022/11/2 9:57
 */
@Slf4j
@Component
public class UserGoOnlineEventListener {
    
    @Autowired
    private SpringWebSocket springWebSocket;
    
    @EventListener
    public void server(UserGoOnlineEvent event){
        log.info("上线通知发送开始--------------------------");
        LoginUser user = event.getLoginUser();
        List<LoginUser> users = springWebSocket.getOnlineUser();
        for (LoginUser loginUser : users) {
            //告诉其他用户我已在线
            Map<String,Object> map = new HashMap<>();
            map.put("userInfo",user);
            Result resp = Result.SUCCESS(map);
            resp.setCode(WebSocketConstant.ON_LINE);
            springWebSocket.readyMessage(loginUser.getUserId(), JSON.toJSONString(resp));
        }
        //告诉我其他已在线用户
        Map<String,Object> map = new HashMap<>();
        map.put("userInfos",users);
        Result resp = Result.SUCCESS(map);
        resp.setCode(WebSocketConstant.MULTIPLAYER_ONLINE);
        springWebSocket.readyMessage(user.getUserId(),JSON.toJSONString(resp));
        log.info("上线通知发送结束--------------------------");
    }
}
